<?php

namespace App\Http\Controllers\Api;

use App\Services\Api\ApiService;
use App\Services\PermissionService;
use App\Services\RoleService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends Controller
{
    private $service;

    public function __construct(ApiService $apiService, RoleService $service)
    {
        parent::__construct($apiService);
        $this->service = $service;
    }

    /**
     * 查询角色(带分页)
     * @return mixed
     */
    public function index(){
        $showPage = $this->getShowPage();
        if (!empty(request()->input('showpage'))){
            $showPage = request()->input('showpage');
        }
        $data = $this->service->repository->paginate($showPage);
        return $this->apiService->run(200, $data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id){
        $data = $this->service->repository->find($id);
        return $this->apiService->run(200, $data);
    }

    /**
     * 创建角色
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request){
        $role = $this->service->repository->create($request->all());
        return $this->apiService->run(200, $role);
    }

    /**
     * 修改角色
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request, $id){
        $role = $this->service->repository->find($id)->update($request->all());
        return $this->apiService->run(200, $role);
    }

    /**
     * 删除角色
     * @param $id
     * @return mixed
     */
    public function destroy($id){
        $this->service->repository->delete($id);
        return $this->apiService->run(200);
    }

    /**
     * 角色绑定权限
     * @param $id
     * @param $permission_id
     * @param PermissionService $permissionService
     * @return mixed
     */
    public function roleBindPermission($id, $permission_id, PermissionService $permissionService){
        $role = $this->service->repository->find($id)->attachPermission(
            $permissionService->repository->find($permission_id)
        );
        return $this->apiService->run(200, $role);
    }

    /**
     * 角色移除一个权限
     * @param $id
     * @param $permission_id
     * @param PermissionService $permissionService
     * @return mixed
     */
    public function roleRemovePermission($id, $permission_id, PermissionService $permissionService){
        $role = $this->service->repository->find($id)->detachPermission(
            $permissionService->repository->find($permission_id)
        );
        return $this->apiService->run(200, $role);
    }

    /**
     * 角色移除所有权限
     * @param $id
     * @return mixed
     */
    public function roleRemoveAllPermission($id){
        $role = $this->service->repository->find($id)->detachAllPermissions();
        return $this->apiService->run(200, $role);
    }

}
